
from google.appengine.ext.webapp import template

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from google.appengine.ext import db
import re,os
import datastore
import library
import datetime

from google.appengine.api import users

class Person():
  fname=""
  lname=""
  roster=""

  def fname(self):
    return "roger"
  def lname(self):
    return "okamoto"
  def roster(self):
    return "1-3-2011"


class USTATeam():

  def __init__(self,position,name,captain):
   self.position=position
   self.name = name
   self.captain = captain
   self.members = []

  def addmember(self, p ):
   self.members.append(p)  

  def getmembers(self):
   return self.members



class MainPage(webapp.RequestHandler):

    def Write(self,t):
       self.response.out.write(t)


    def Links(self ,idx):
       library.Links(self,idx,"yes")  # any non-null means to add ?facility= to the link

    def ScrapeTeam(self , facilityid,idx, name, captain):
       return library.scrapeteam(self ,facilityid, idx, name,captain)

    def Table(self)  :
       self.Write( '<table align="center"  class="sortable" >')

    def EndTable(self)  :
       self.Write( '</table>')

    def DoHeader(self):
#      self.Write( '<thead>')
       self.Write( '<tr>')
       self.Write( '<th scope="col">First Name</th>')
       self.Write( '<th scope="col">Last Name</th>')
       self.Write( '<th scope="col">City</th>')
#      self.Write( '<th scope="col">USTA #</th>')
       self.Write( '<th scope="col">NTRP</th>')
       self.Write( '<th scope="col">Roster</th>')
#      self.Write( '<th scope="col">CTC</th>')
#      self.Write( '<th scope="col">CSC</th>')
       self.Write( '</tr>')
#      self.Write( '</thead>')

    def DoLastRosteredHeader(self):
#      self.Write( '<thead>')
       self.Write( '<tr>')
       self.Write( '<th scope="col">Date</th>')
       self.Write( '<th scope="col">First Name</th>')
       self.Write( '<th scope="col">Last Name</th>')
       self.Write( '<th scope="col">Team</th>')
       self.Write( '<th scope="col">Captain</th>')
       self.Write( '</tr>')
#      self.Write( '</thead>')

    def TripleCell( self,data):
	self.response.out.write('<td valign="middle" colspan=8 width="500" ALIGN=LEFT>'+data+'&nbsp</td>')

    def Cell( self,data):
       self.Write( '<td>' + str(data) + '</td>');

    def get(self):
        fac =  self.request.get('facility') 
        facilityid,facility = library.getfacilityNameID( fac)


        self.response.headers['Content-Type'] = 'text/html'


        self.Write('<html>')
        self.Write('<center>')
        self.Write('<title>' + facility + ' Players</title>')
        self.Write('<h1>'+ facility + ' USTA Rosters</h1>')
        self.Write('<style type="text/css>">')
        self.Write('<!--')
        self.Write('@import url("css/patc.css")' )
        self.Write('-->')
        self.Write('</style>')
        self.Write('</head>')

        level =  self.request.get('level') 
        level = level.lower()
        if( level == ''):
              level = 'Mx8.0'

#       Regular expression to limit teams (not simple to put team level into datastore model)
        reg = "( " + level + ")"

        self.Links(facilityid)

        query="select __key__ from FacilityTeam where facility= " + facilityid + " order by position"

#       Override if want to get a bunch of teams faster
        start =  self.request.get('start') 
        end =  self.request.get('end') 
        if( start!="" and end!=""):
          query  = "select __key__ from FacilityTeam where facility= " + facilityid 
          query += " and position>= " + start + " and position <=" + end + " order by position"
          reg=".*"

        self.Write(query+'<br>')
        self.Write('select by '+ reg +'<br>')

        allkeys =  db.GqlQuery( query )

#       User reg to set the search team '( M3.5)'       
        regexp = re.compile( reg, re.IGNORECASE)    
        teams=[]

        for key in allkeys:
           t = db.get(key)
           found = regexp.findall( t.name )  
           if( found):
               teams.append(key)                

        for k in teams:
#          Save this update time
           t = db.get(k)
           t.updated = datetime.datetime.now() - datetime.timedelta( hours = 7 )
           db.put(t)

#          Get the current players on this team
#          rlist: list of Roster() classes for each player on this team
           rlist,rosterlen,playerlen = self.ScrapeTeam( facilityid, t.teamid , t.name,  t.captain)

#          STOP - ERROR HERE!!! empty rlist
           if( rlist == None):
              self.Write("LIKELY A MISMATCH in rostered date/name")
              return

           self.Write( '<br>' + str(t.teamid) + " " +  t.name + " " + t.captain + " " + str(rosterlen) + ' ' + str(playerlen) + '<br>')


# Remove anyone who already on the team from prior rlist
           query='select __key__ from FacilityRoster where teamid = ' + str(t.teamid) + ' order by lname'
           rosterkeys = list( db.GqlQuery( query ))

           for r in rlist:
              if (r.key() in rosterkeys ):
                  t = db.get(r.key())
                  rosterkeys.remove(r.key())

# What is left is player who unregisted from the team
           self.Write( 'unreg =  ' + str(len(rosterkeys))  + '<br>' )           
           for r in rosterkeys:
              t = db.get(r)
              self.Write('delete unregisted player ' + t.fname + ' ' + t.lname +  '<br>')
              db.delete(r)               

# Add team members (duplicates won't be added )
           if(rlist != None):
                for r in rlist:
                   self.Write( str(r.playerid) + ') ' + r.fname+' '+ r.lname + ' ' + r.city + ' ' + r.gender )
                   self.Write( ' ' + r.rating + ' ' + r.roster + ' ' + str(r.date)  + '<br>' )

                db.put(rlist)
#  ------------------------------------------------------------------------------------
    def get_prev(self):

        fac =  self.request.get('facility') 
        facilityid,facility = library.getfacilityNameID( fac)


        self.response.headers['Content-Type'] = 'text/html'


        self.Write('<html>')
        self.Write('<center>')
        self.Write('<title>' + facility + ' Players</title>')
        self.Write('<h1>'+ facility + ' USTA Rosters</h1>')
        self.Write('<style type="text/css>">')
        self.Write('<!--')
        self.Write('@import url("css/patc.css")' )
        self.Write('-->')
        self.Write('</style>')
        self.Write('</head>')

        level =  self.request.get('level') 
        level = level.lower()
        if( level == ''):
              level = 'cm65'

        reg = "( M3.5)";

# Translate update?level=M35 to regular expression
#       dict = library.dict
#       reg = dict[level]

        reg = "( " + level + ")"

        self.Links(facilityid)


#       LAST ROSTERED -------------------------------------------------------
        if( reg == "last"):
          query="select * from FacilityRoster where facility " + facilityid  +" order by date desc , lname  limit 50"
          lastrostered =  db.GqlQuery( query )          

# TODO  change * to __key__
          for l in lastrostered:
              query="select * from FacilityTeam where teamid=" + str(l.teamid) 
              c =  db.GqlQuery( query )          
              self.Write(l.roster + ' ' +l.fname + ' ' +l.lname + ' ' + c[0].name + ' ' +c[0].captain + '<br>')

          return


#       UPDATE ---------------------------------------------------------------


        query="select __key__ from FacilityTeam where facility= " + facilityid + " order by position"

        allkeys =  db.GqlQuery( query )

#       User reg to set the search team '( M3.5)'       
        regexp = re.compile( reg, re.IGNORECASE)    
        teams=[]

        for key in allkeys:
           t = db.get(key)
           found = regexp.findall( t.name )  
           if( found):
               teams.append(key)                

        for k in teams:
#          Save this update time
           t = db.get(k)
           t.updated = datetime.datetime.now() - datetime.timedelta( hours = 7 )
           db.put(t)

#          Get the current players on this team
#          rlist: list of Roster() classes for each player on this team
           rlist,rosterlen,playerlen = self.ScrapeTeam( facilityid, t.teamid , t.name,  t.captain)

#          STOP - ERROR HERE!!! empty rlist
           if( rlist == None):
              self.Write("LIKELY A MISMATCH in rostered date/name")
              return

           self.Write( '<br>' + str(t.teamid) + " " +  t.name + " " + t.captain + " " + str(rosterlen) + ' ' + str(playerlen) + '<br>')


# Remove anyone who already on the team from prior rlist
           query='select __key__ from FacilityRoster where teamid = ' + str(t.teamid) + ' order by lname'
           rosterkeys = list( db.GqlQuery( query ))

           for r in rlist:
              if (r.key() in rosterkeys ):
                  t = db.get(r.key())
                  rosterkeys.remove(r.key())

# What is left is player who unregisted from the team
           self.Write( 'unreg =  ' + str(len(rosterkeys))  + '<br>' )           
           for r in rosterkeys:
              t = db.get(r)
              self.Write('delete unregisted player ' + t.fname + ' ' + t.lname +  '<br>')
              db.delete(r)               

# Add team members (duplicates won't be added )
           if(rlist != None):
                for r in rlist:
                   self.Write( str(r.playerid) + ') ' + r.fname+' '+ r.lname + ' ' + r.city + ' ' + r.gender )
                   self.Write( ' ' + r.rating + ' ' + r.roster + ' ' + str(r.date)  + '<br>' )

                db.put(rlist)


application = webapp.WSGIApplication(
                                     [('/update', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":

#   print __file__
#   print __name__

    main()
